//
//  CommentViewModel.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/24/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import Foundation


final class CommentViewModel {
    private let backendService = Backend()
    var nextURL: String?
    
    public var comments: [AdvertComment] = []

}

extension CommentViewModel {
    
    public func loadComments (id: Int, completion: @escaping (Result<Bool, RequestError>) -> Void) {
        let request = self.getRequest(id: id)
        
        backendService.fetchFromBackend(for: Response<[AdvertComment]>.self, request: request, statusCode: 200, sendBool: false) { (result) in
            switch result {
                case .failure(let err):
                    completion(.failure(err))
                case .success(let response):
                    self.nextURL = response.next
                    self.comments.insert(contentsOf: response.results.reversed(), at: 0)
                    completion(.success(true))
            }
        }
    }
    
    public func sendComment (text: String, replyId: Int?, advert: Int, completion: @escaping (Result<Bool, RequestError>) -> Void)  {
        var request = URLRequest(url: Request(base: .advert).getUrl(path: "adverts/my/comments/"))
        
        let data = ["text": text, "advert": advert, "parent": replyId] as [String : Any?]

        if let body = try? JSONSerialization.data(withJSONObject: self.getBody(data), options: []) {
            request.httpMethod = "POST"
            request.httpBody = body
            
            backendService.fetchFromBackend(for: AdvertComment.self, request: request, statusCode: 201, sendBool: false) { (result) in
                switch result {
                case .failure(let err):
                    completion(.failure(err))
                case .success(let comment):
                    self.comments.append(comment)
                    completion(.success(true))
                }
            }
        } else {
            completion(.failure(.general))
        }
    }
    
    
    
    
    private func getRequest (id: Int) -> URLRequest {
        if nextURL != nil, let url = URL(string: nextURL!) {
            return URLRequest(url: url)
        } else {
            return URLRequest(url: Request(base: .advert).getUrl(path: "adverts/\(id)/comments/"))
        }
    }
    private func getBody (_ data: [String: Any?]) -> [String:Any] {
        var output: [String:Any] = [:]
        for key in data.keys {
            if let _el = data[key] {
                if _el != nil {
                    output[key] = _el!
                }
            }
        }
        return output
    }
}
